import DataMgr from "../mgr/dataManager";
import GameMgr from "../mgr/gameManager";
import NativeMgr from "../mgr/nativeManager";
import NetMgr from "../mgr/netManager";
import SoundMgr from "../mgr/soundManager";
import { subGameMgr } from "../mgr/SubGameMgr";



const { ccclass, property, executionOrder } = cc._decorator;

@ccclass
@executionOrder(-15)
export default class PermanentNode extends cc.Component {

    // @property(cc.Label)
    // label: cc.Label = null;
    //
    // @property
    // text: string = 'hello';
    time: number;
    isClick: boolean = false;
    channel: string;
    hasRegistVoiceEvent: boolean = false;
    // LIFE-CYCLE CALLBACKS:

    onLoad() {


        console.log('init PermanentNode')
        cc.game.targetOff(this);
        cc.systemEvent.targetOff(this);

        cc.systemEvent.on(cc.SystemEvent.EventType.KEY_DOWN, this.onKeyDown.bind(this), this);

        cc.systemEvent.on('android_keyDown', this.onKeyDownNew.bind(this), this);
        cc.systemEvent.on("OnKeyboardReturn", this.OnKeyboardReturn.bind(this), this);

        cc.systemEvent.on("getEcpm", this.OnGetEcpm.bind(this), this);


        cc.systemEvent.on('backHome', () => {
            subGameMgr.exitSubGame();
            NativeMgr.Ins().showFullAds();
        }, this);


        cc.systemEvent.on('showExpressAdInGame', (data) => {
            NativeMgr.Ins().showExpressAds(data);
        }, this);

        cc.systemEvent.on('rankPost', (data) => {
            // cc.systemEvent.emit('rankPost', { type: "moreMoney", score: cc.Mgr.UserDataMgr.HistoryHighAssets })
            NetMgr.Ins().postRankList(data.type, data.score)
        }, this);


        cc.game.on(cc.game.EVENT_HIDE, () => {
            console.log('游戏进入后台');
            SoundMgr.Ins().pauseAllSound();

            GameMgr.Ins().emit('hideGame', {});


        }, this);

        cc.game.on(cc.game.EVENT_SHOW, () => {
            console.log('重新返回游戏');
            SoundMgr.Ins().resumeAllSound();

            GameMgr.Ins().emit('showGame', {});


        }, this);




        this.adsEvent()


        cc.systemEvent.on('copyClipboard', (data) => {
            console.log('copyClipboard = ', data);

        }, this);

        cc.systemEvent.on('getSceneData', (data) => {
            console.log('getSceneData = ', data);
            if (data && data !== "") {
                DataMgr.Ins().setLocalStorage('sceneData', data);
            }

        }, this);

        const invite = NativeMgr.Ins().getInviteInfo();
        if (invite && invite !== "") {
            DataMgr.Ins().setLocalStorage('sceneData', invite);
        }

    }

    protected OnKeyboardReturn() {
        cc.systemEvent.emit("OnKeyboardEnter");
    }

    onKeyDown(event) {

        console.log('onkeyDown = ' + JSON.stringify(event));
        console.log('keyCode = ', event.keyCode);
        switch (event.keyCode) {
            //注意Creator版本为2.x的请把cc.KEY.back。修改成cc.macro.KEY.back
            case cc.macro.KEY.back:
            case cc.macro.KEY.r:
                if (GameMgr.Ins().wantEndGame) {
                    return;
                }
                GameMgr.Ins().wantEndGame = true;

                GameMgr.Ins().showMsg("确定要退出游戏吗？", '确定', '取消', () => {
                    cc.game.end();
                    GameMgr.Ins().wantEndGame = false;
                }, () => {
                    GameMgr.Ins().wantEndGame = false;
                })

                break;
            case cc.macro.KEY.enter:
                cc.systemEvent.emit("OnKeyboardEnter");
                break;
        }
    }


    async onKeyDownNew(event) {
        console.log('onkeyDown = ' + JSON.stringify(event));
        console.log('keyCode = ', event.keyCode);
        switch (event) {
            //注意Creator版本为2.x的请把cc.KEY.back。修改成cc.macro.KEY.back
            case "4":
                if (GameMgr.Ins().wantEndGame) {
                    return;
                }
                GameMgr.Ins().wantEndGame = true;
                // cc.gm.emit(Local_Event_Name.androidKeyBack,{});
                GameMgr.Ins().showMsg("确定要退出游戏吗？", '确定', '取消', () => {
                    cc.game.end();
                    GameMgr.Ins().wantEndGame = false;
                }, () => {
                    GameMgr.Ins().wantEndGame = false;
                })
                return;
            case '24':  //音量增加
            case '25':  //音量减少

                return;
            case '26':  //电源键
                break;
            case '91':  //话筒静音
                break;
            case '164':  //扬声器静音
                break;
        }
    }


    async OnGetEcpm(event) {
        console.log('OnGetEcpm = ' + JSON.stringify(event));

        const info = await NetMgr.Ins().post('watchAds', event)
        DataMgr.Ins().refreshUserInfo(info);
        GameMgr.Ins().unblock();
        // GameMgr.Ins().showMsg('获得的积分'+event);
        this.isClick = false;
        const infoStr = event.split('_');
        if (infoStr.length > 2) {
            cc.systemEvent.emit(infoStr[0], infoStr[1]);
        }


    }


    protected onDestroy(): void {

        console.log('preNode destroy')
    }





    adsEvent() {
        cc.systemEvent.on('openAds', (data) => {
            console.log('openAds = ', Number(data));


        }, this);

        cc.systemEvent.on('bannerAds', (data) => {
            console.log('bannerAds = ', Number(data));

        }, this);

        cc.systemEvent.on('rewardAds', (data) => {
            console.log('rewardAds = ', Number(data));

            this.httpRequest({ event: 'reward', source: NativeMgr.Ins().channel() })
        }, this);

        cc.systemEvent.on('fullAds', (data) => {
            console.log('fullAds = ', Number(data));

        }, this);

        cc.systemEvent.on('expressAds', (data) => {
            console.log('expressAds = ', Number(data));


        }, this);




        cc.systemEvent.on("RewardWaitting", () => {
            console.log('视频广告正在加载中。。。');
            
        }, this);
        cc.systemEvent.on("onAdFailed", (data) => {
            GameMgr.Ins().unblock();
            console.log(`视频加载失败，类型:${data}`);
            const infoArr = data.split('_');
            const type = infoArr[0];
            const code = infoArr[1];
            const msg = infoArr[2];
            /**
             * 报错
             *
             * post http://domain:8086/logger/error
             *    {message:'xxx', stack:'xxx', appid:'xxx', unionid:'xxx', uid:'xxx', content:{}}
             */


            NetMgr.Ins().servo.post('/logger/error', {
                message: msg,
                stack: code,
                appid: NativeMgr.Ins().appId(),
                unionid: NativeMgr.Ins().deviceId(),
                uid: DataMgr.Ins().uid || '',
                content: { type, code, msg }
            }, true);



        }, this);

        cc.systemEvent.on("onAdClick", (data) => {
            if (this.isClick) {
                return;
            }
            this.httpRequest({ event: 'click', source: NativeMgr.Ins().channel() })
            this.isClick = true;
        }, this);
    }




    httpRequest(options) {

        const deviceId = NativeMgr.Ins().deviceId();
        const appId = NativeMgr.Ins().appId();
        this.channel = NativeMgr.Ins().channel();

        options.appid = appId;
        options.unionid = deviceId;
        options.worth = Number(options.worth) > 0 ? Number(options.worth) : 0


        console.log('httpSend = ', options);
        NetMgr.Ins().servo.post('/payment/advertising/transaction', options, true);


    }
    // update (dt) {}
}
